﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using System;
using System.Diagnostics;
using MoreEPG.Helper;
using MCHelp;
using Microsoft.MediaCenter.Guide;
using System.Collections.Generic;
using System.ComponentModel;
using GalaSoft.MvvmLight.Messaging;

namespace MoreEPG.ViewModel
{
   
    public class MCToolsViewModel : ViewModelBase
    {
        private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
        private Core _Core = Core.Instance;
        private MCConnection Con;
        private string mcupdate = Environment.GetEnvironmentVariable("windir") + @"\ehome\mcupdate.exe";
        private string schtask = Environment.GetEnvironmentVariable("windir") + @"\system32\schtasks.exe";
        private string arg;
        private job befehl;
        private bool ButtonCanExecute = true;

        /// <summary>
        /// Initializes a new instance of the MCToolsViewModel class.
        /// </summary>
        public MCToolsViewModel()
        {
            this.Con = _Core.MCCon;
            this.InitCommands();

        }


        #region Fields

        public const string VisibilityPropertyName = "visibility";

        private bool _visibility = false;

        public bool visibility
        {
            get
            {
                return _visibility;
            }

            set
            {
                if (_visibility == value)
                {
                    return;
                }


                _visibility = value;


                // Update bindings, no broadcast
                RaisePropertyChanged(VisibilityPropertyName);

            }
        }

        #endregion

        #region Commands

        public RelayCommand ResetMC
        {
            get;
            private set;
        }

        public RelayCommand ResetEPG
        {
            get;
            private set;
        }

        public RelayCommand ReindexEPG
        {
            get;
            private set;
        }

        public RelayCommand DelLogos
        {
            get;
            private set;
        }

        public RelayCommand DelChannels
        {
            get;
            private set;
        }

        #endregion

        #region Private Methods

        private void InitCommands()
        {
            this.ResetMC = new RelayCommand(
                () => OnResetMC(),
                () => ButtonCanExecute);
            this.ResetEPG = new RelayCommand(
                () => OnResetEPG(),
                () => ButtonCanExecute);
            this.ReindexEPG = new RelayCommand(
                () => OnReindexEPG(),
                () => ButtonCanExecute);
            this.DelLogos = new RelayCommand(
                () => OnDelLogos(),
                () => ButtonCanExecute);
            this.DelChannels = new RelayCommand(
                () => OnDelChannels(),
                () => ButtonCanExecute);
        }

        private void OnDelChannels()
        {
            var message = new CustomDialogMessage("Wollen Sie die MoreEPG Channels löschen ?", CustomMessageBoxImage.Alert, CustomMessageBoxButton.YesNo, OnDelChannelsCallback);
            Messenger.Default.Send(message);
        }
        private void OnDelChannelsCallback(CustomDialogMessageResult result)
        {
            if (result == CustomDialogMessageResult.Yes)
            {
                logger.Debug("## Die MoreEPG Channels werden gelöscht ! ##");
                this.befehl = job.DeleteChannels;
                this.DoProcessing();
            }

        }

        private void OnDelLogos()
        {
            var message = new CustomDialogMessage("Die Sender Logos werden gelöscht !", CustomMessageBoxImage.Information, CustomMessageBoxButton.OKCancel, OnDelLogosCallback);
            Messenger.Default.Send(message);
        }
        private void OnDelLogosCallback(CustomDialogMessageResult result)
        {
            if (result == CustomDialogMessageResult.OK)
            {
                logger.Debug("## Die Sender Logos werden gelöscht ! ##");
                this.befehl = job.DeleteLogos;
                this.DoProcessing();
            }

        }

        private void OnReindexEPG()
        {
            var message = new CustomDialogMessage("Der Such-Index wird neu erstellt !", CustomMessageBoxImage.Information, CustomMessageBoxButton.OKCancel, OnReindexEPGCallback);
            Messenger.Default.Send(message);
        }
        private void OnReindexEPGCallback(CustomDialogMessageResult result)
        {
            if (result == CustomDialogMessageResult.OK)
            {
                logger.Debug("## der Index wird neu erstellt ! ##");
                this.arg = " /run /tn \"\\Microsoft\\Windows\\Media Center\\ReindexSearchRoot\"";
                this.befehl = job.Reindex;
                this.DoProcessing();
            }

        }

        private void OnResetEPG()
        {
            var message = new CustomDialogMessage("Wollen Sie das EPG Reseten ?", CustomMessageBoxImage.Alert, CustomMessageBoxButton.YesNo, OnResetEPGCallback);
            Messenger.Default.Send(message);
        }
        private void OnResetEPGCallback(CustomDialogMessageResult result)
        {
            if (result == CustomDialogMessageResult.Yes)
            {
                logger.Debug("## das EPG wird resettet ! ##");
                this.arg = " -ObjectStoreRecoveryTask";
                this.befehl = job.ResetEPG;
                this.DoProcessing();
            }

        }
        

        private void OnResetMC()
        {
            var message = new CustomDialogMessage("Wollen Sie das Media Center Reseten\n(alle Einstellungen gehen verloren!) ?", CustomMessageBoxImage.Alert, CustomMessageBoxButton.YesNo, OnResetMCCallback);
            Messenger.Default.Send(message);
        }
        private void OnResetMCCallback(CustomDialogMessageResult result)
        {
            if (result == CustomDialogMessageResult.Yes)
            {
                logger.Debug("## das MC wird resettet ! ##");
                this.arg = " -MediaCenterRecoveryTask";
                this.befehl = job.ResetMC;
                this.DoProcessing();
            }

        }

        private void ToggleButtonCanExecute(bool State)
        {
            this.ButtonCanExecute = State;
            ResetMC.RaiseCanExecuteChanged();
            ResetEPG.RaiseCanExecuteChanged();
            ReindexEPG.RaiseCanExecuteChanged();
            DelLogos.RaiseCanExecuteChanged();
            DelChannels.RaiseCanExecuteChanged();
        }

        /// <summary>
        /// Start Worker Thread
        /// </summary>
        private void DoProcessing()
        {
            BackgroundWorker Run = new BackgroundWorker();
            Run.DoWork += new DoWorkEventHandler(Run_DoWork);
            Run.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Run_RunWorkerCompleted);
            this.visibility = true;
            //this.Cursor = Cursors.Wait;
            this.ToggleButtonCanExecute(false);
            Run.RunWorkerAsync();
        }

        private void Run_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.ToggleButtonCanExecute(true);
            this.visibility = false;
            CustomDialogMessage message = null;
            if (e.Error != null)
            {
                message = new CustomDialogMessage("Ein Fehler ist aufgetreten :\n" + e.Error.Message, CustomMessageBoxImage.Error, CustomMessageBoxButton.OK, null);
            }
            else
            {
                message = new CustomDialogMessage("Fertig", CustomMessageBoxImage.Information, CustomMessageBoxButton.OK, null);
            }
            Messenger.Default.Send(message);
        }

        private void Run_DoWork(object sender, DoWorkEventArgs e)
        {
           
            if (this.befehl == job.ResetMC)
            {
                this.resetMC();
            }
            else if (this.befehl == job.ResetEPG)
            {
                this.DeleteEPG();
            }
            else if (this.befehl == job.Reindex)
            {
                this.StartReindex();
            }
            else if (this.befehl == job.DeleteLogos)
            {
                this.DeleteLogos();
            }
            else if (this.befehl == job.DeleteChannels)
            {
                this.DeleteChannels();
            }
            
        }

        private void StartReindex()
        {
            Process proc = new Process();
            ProcessStartInfo Startinfo = new ProcessStartInfo(this.schtask);
            Startinfo.Arguments = this.arg;
            Startinfo.CreateNoWindow = true;
            Startinfo.WindowStyle = ProcessWindowStyle.Hidden;
            proc.StartInfo = Startinfo;
            try
            {
                proc.Start();
                proc.WaitForExit();
            }
            catch (Exception ex)
            {
                logger.Error("Error bei MCTools : " + ex.Message);
            }
        }

        private void resetMC()
        {
            Process proc = new Process();
            ProcessStartInfo Startinfo = new ProcessStartInfo(this.mcupdate);
            Startinfo.Arguments = this.arg;
            Startinfo.CreateNoWindow = true;
            Startinfo.WindowStyle = ProcessWindowStyle.Hidden;
            proc.StartInfo = Startinfo;
            try
            {
                proc.Start();
                proc.WaitForExit();
            }
            catch (Exception ex)
            {
                logger.Error("Error bei MCTools : " + ex.Message);
            }
        }

        private void DeleteLogos()
        {
            if (this.Con == null)
            {
                throw new Exception("MCConnection is Null !");
            }
            Services ser = new Services(this.Con.Store);
            foreach (Service n in ser)
            {
                n.LogoImage = null;
                n.Update();
            }
        }

        private void DeleteEPG()
        {

            Process proc = new Process();
            ProcessStartInfo Startinfo = new ProcessStartInfo(this.mcupdate);
            Startinfo.Arguments = this.arg;
            Startinfo.CreateNoWindow = true;
            Startinfo.WindowStyle = ProcessWindowStyle.Hidden;
            proc.StartInfo = Startinfo;
            try
            {
                proc.Start();
                proc.WaitForExit();
            }
            catch (Exception ex)
            {
                logger.Error("Error bei MCTools : " + ex.Message);
            }

        }

        private void DeleteChannels()
        {
            if (this.Con == null)
            {
                throw new Exception("MCConnection is Null !");
            }
            List<Channel> removedChannels = new List<Channel>();
            foreach (Channel chan in this.Con.Tvm2W7Lineup.GetChannels())
            {
                try
                {
                    this.Con.Tvm2W7Lineup.RemoveChannel(chan);
                    removedChannels.Add(chan);
                }
                catch (Exception ex)
                {
                    logger.Error("Error bei MCTools : " + ex.Message);
                }

            }
            this.Con.Tvm2W7Lineup.NotifyChannelsRemoved(removedChannels);

        }

        #endregion
    }
}